package it.webrules.deploymanager.core.st.scm;

import it.webrules.deploymanager.core.HookException;
import it.webrules.deploymanager.core.HookManager;
import it.webrules.deploymanager.core.MailService;
import it.webrules.xsd.dmc.config.v1.ExecuteCommand;
import it.webrules.xsd.dmc.config.v1.SendEmail;
import it.webrules.xsd.dmc.config.v1.StaticAction;
import it.webrules.xsd.dmc.config.v1.StaticConfig;
import it.webrules.xsd.dmc.config.v1.StaticHook;

import java.util.List;

public class StaticHookManager extends HookManager {

	private final StaticConfig staticConfig;

	public StaticHookManager(StaticConfig staticConfig) {
		this.staticConfig = staticConfig;
	}

	public void beforestart() throws HookException {
		StaticHook beforestart = staticConfig.getBeforestart();
		exechook(beforestart);
	}

	public void afterend() throws HookException {
		StaticHook afterend = staticConfig.getAfterend();
		exechook(afterend);
	}

	private void exechook(StaticHook hook) throws HookException {

		if (hook == null)
			return;

		List<StaticAction> actions = hook.getAction();
		for (StaticAction action : actions) {
			doAction(action);
		}
	}

	private void doAction(StaticAction action) throws HookException {

		MailService mailService = new MailService(staticConfig.getConfig());

		for (Object actchoosen : action.getSendemailOrExec()) {
			if (actchoosen instanceof SendEmail) {
				sendmail(mailService, actchoosen);
			} else if (actchoosen instanceof ExecuteCommand) {
				execCommand(actchoosen);
			}
		}

	}
}
